import { _window } from '../global.ts'

export interface _scrollPotion {
  behavior?: 'auto' | 'instant' | 'smooth'
  left?: number
  top?: number
}
/**
 * vue-route savedPosition only remenber window scrollPostion
 * mySavedPostion is used to extend the remenber scrollPostion capacity
 */
class MySavedPostion {
  private scrollPositions = new Map<string, _scrollPotion>()
  private targetEl?: HTMLElement
  private postionEl?: string
  defaultPostion: _scrollPotion = {
    left: 0,
    top: 0,
    behavior: 'smooth',
  }

  init(el: string) {
    this.postionEl = el
  }

  // Save route scrollbar records
  saveScrollPostion(key: string, option?: _scrollPotion): void {
    if (!this.targetEl) {
      if (!this.postionEl) {
        _window._log.wran('You had forgot init before saveScrollPostion')
        return
      } else {
        const el = document.querySelector(this.postionEl)
        if (!el) {
          _window._log.wran(`Couldn't find element using selector "${this.postionEl}".`)
          return
        }
        this.targetEl = el as HTMLElement
      }
    }
    const ScrollY = this.targetEl ? (this.targetEl.scrollTop ?? 0) : 0
    const ScrollX = this.targetEl ? (this.targetEl.scrollLeft ?? 0) : 0
    this.scrollPositions.set(key, {
      left: ScrollX,
      top: ScrollY,
      ...option,
    })
  }

  // Retrieve and save route scrolling records
  getScrollPostion(key: string) {
    const scroll = this.scrollPositions.get(key) ?? this.defaultPostion
    this.scrollPositions.delete(key)
    return scroll
  }

  // scrollTo
  scrollTo(key: string) {
    const options: _scrollPotion = this.getScrollPostion(key)
    requestAnimationFrame(() => {
      if (this.targetEl) {
        this.targetEl.scrollTo(options)
      } else {
        window.scrollTo({
          left: options.left != null ? options.left : window.scrollX,
          top: options.top != null ? options.top : window.scrollY,
          behavior: options.behavior ?? 'smooth',
        })
      }
    })
  }
}
const _mySavedPostion = new MySavedPostion()

export default _mySavedPostion
